package gui;

import gui.clock.AbstractClock;
import gui.clock.ClockControl;
import gui.clock.ClockDisplay;
import gui.clock.FakeClock;
import java.awt.Component;
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import java.util.List;
import javax.swing.BorderFactory;
import javax.swing.Box;
import javax.swing.BoxLayout;
import javax.swing.JButton;
import javax.swing.JPanel;
import query.Interpolation;
import query.Query;
import simulation.EarthClone;
import storage.SamplingAccuracyInterpreter;
import storage.beans.CellBean;
import storage.beans.GridBean;
import storage.beans.SimulationBean;
import common.EarthSimSettings;
import common.ICell;

public class QueryRunPanel extends JPanel implements ActionListener {
  private static final long serialVersionUID = -768778137113401918L;
  private EarthSimSettings settings = EarthSimSettings.getInstance();
  private static final String START = "Run Query";
  private static final String PAUSE = "Pause";
  private static final String RESET = "Reset";
  
  private JButton btnRun;
  private EarthPanel pnlEarth;
  private AbstractClock clock;
  private ClockDisplay clockDisplay;
  private UserControlPanel pnlUserControls;
  
  public QueryRunPanel(EarthPanel pnlEarth, UserControlPanel pnlUserControls, ClockDisplay clockDisplay) {
    super();
    this.pnlEarth = pnlEarth;
    this.pnlUserControls = pnlUserControls;
    this.clockDisplay = clockDisplay;
    settings.setRunPanelReference(this);
    
    setLayout(new BoxLayout(this, BoxLayout.PAGE_AXIS));
    setBorder(BorderFactory.createTitledBorder("Query Controls"));
    
    Dimension dim = new Dimension(190,90);
    setPreferredSize(dim);
    setMaximumSize(dim);

    btnRun = new JButton(START);
    btnRun.addActionListener(this);
    btnRun.setActionCommand(START);
    
    JButton btnReset = new JButton(RESET);
//    btnReset.setSize(new Dimension(100, 20));
//    btnReset.setPreferredSize(new Dimension(100, 20));
    btnReset.addActionListener(this);
    btnReset.setActionCommand(RESET);
    
    btnRun.setAlignmentX(Component.CENTER_ALIGNMENT);
    btnReset.setAlignmentX(Component.CENTER_ALIGNMENT);
    add(btnRun);
    add(Box.createRigidArea(new Dimension(10,10)));
    add(btnReset);
  }
  
  public AbstractClock getClock() {
    return clock;
  }
  
  public void resetRunButton() {
    setRunButton(START);
  }
    
  public void actionPerformed(ActionEvent evt) {
    if(evt.getActionCommand().equals(START)) {
      setRunButton(PAUSE);
      if(settings.isQueryRunning()) {
        settings.hideStats();
        clock.start();
      }
      else {
        System.out.println(settings);
        try {
          Query query = new Query(settings.getTilt(), 
                                  settings.getEccentricity(), 
                                  settings.getStartDateTime(), 
                                  settings.getEndDateTime());
          SimulationBean storedBean = query.run();
          if(storedBean == null) {
            pnlUserControls.disableQueryControls();
            clock = new ClockControl(pnlEarth, clockDisplay);
            clockDisplay.setClockType(clock);
            clock.start();
          }
          else {
            //do something with the stored settings
            ArrayList beanList = new ArrayList();
            SamplingAccuracyInterpreter ai = new SamplingAccuracyInterpreter(settings.getSamplingRate());
            storedBean.initGridIterator();
            for(GridBean gb = storedBean.getNextGrid(); gb != null; gb = storedBean.getNextGrid()) {
              int cellsPerRow = Integer.parseInt(gb.getWidth());
              int cellsPerCol = Integer.parseInt(gb.getHeight());
              CellBean[][] cellBeans = ai.getGrid(gb.getCellBeanList(), cellsPerCol, cellsPerRow);
              beanList.add(cellBeans);              
            }
            Interpolation ip = new Interpolation();
            List newCellBeanList = Interpolation.run(beanList,
                                                     settings.getGridSpacing(), 
                                                     Integer.parseInt(storedBean.getGridSpacing()),
                                                     Integer.parseInt(storedBean.getTimeStep()), 
                                                     settings.getTimeStep(), 
                                                     Integer.parseInt(storedBean.getRadius()));

            int timeStep = settings.getTimeStep()* 60 * 1000;
            long dateTime = settings.getStartDateTime();
            for(int i = 0; i < newCellBeanList.size(); i++ ) {
              dateTime += timeStep;
              ICell[][] cells = (ICell[][])newCellBeanList.get(i);
              EarthClone earth = new EarthClone(cells, 
              Interpolation.getCellsPerRow(), 
              Interpolation.getCellsPerCol(), 
                                                dateTime, 
                                                settings.getGridSpacing());
              settings.cacheGrid(earth);
            }
            
            clock = new FakeClock(pnlEarth, clockDisplay);
            clockDisplay.setClockType(clock);
            clock.start();
          }
          settings.setQueryRunning(true);      
        }
        catch (Exception e) {
          e.printStackTrace();
        }
      }      
    }
    else if(evt.getActionCommand().equals(PAUSE)) {
      clock.pause();
      setRunButton(START);
      settings.showStats();
//      pnlEarth.enableTooltips();
    }
    else if(evt.getActionCommand().equals(RESET)) {
      if(clock != null) {
        clock.reset();
        setRunButton(START);
        pnlUserControls.enableQueryControls();
        settings.setQueryRunning(false);
  //      pnlEarth.enableTooltips();
      }
    }    
  }
  
  private void setRunButton(String buttonId) {
    btnRun.setText(buttonId);
    btnRun.setActionCommand(buttonId);
  }

}
